import re
import requests
import json
import time
import MysqlDB
from entity.Ticket import Ticket


def writeFile(str):
    file = open("result.txt", "a", 1024, "utf-8")
    file.write("\n========================\n")
    file.write(str)
    file.close()
    print("write end")


def splitStr(s):
    nowDate = time.strftime("%Y%m%d", time.localtime())
    split = re.split(r'[|]', s)
    file = open(nowDate + ".txt", "a", 1024, "utf-8")
    # print(split)
    dataStr = split[0]+","+split[2]+","+split[3]+","+split[11]+","+split[16]+","+split[17]+","+split[18]
    print(dataStr)
    ticket = Ticket(split[0], split[2], split[3], split[11], split[16], split[17], split[18], nowDate)
    MysqlDB.insert(ticket)

    file.write(dataStr)
    file.write("\n")


def test():
    # url = "https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc";
    ticket_query_url = "https://kyfw.12306.cn/otn/leftTicket/query?" \
                       "leftTicketDTO.train_date=2018-12-06" \
                       "&leftTicketDTO.from_station=ZZF" \
                       "&leftTicketDTO.to_station=ZDN" \
                       "&purpose_codes=ADULT"

    response = requests.get(ticket_query_url)
    # 返回的文本
    response_text = response.text
    writeFile(response_text)
    resultJson = json.loads(response_text)
    resultDataList = resultJson['data']['result']
    print(len(resultDataList))
    for s in resultDataList:
        splitStr(s)


if __name__ == '__main__':
    test()




